<?php

    require 'functions.php';
    //session not working
//    session_set_cookie_params(60*60, '/', '.facebook.com');
//    session_start();
//    ob_start();
    
    if (DEBUG==true)
    {
        $output['post'] = json_encode($_POST);
    }
    
    $db = DBControl::getInstance();

    $facebook = new Facebook(array(
      'appId'  => '375403899218810',
      'secret' => 'f9f39624aa0bc78b05a15dcfbfb69abb',
      'cookie' => true
    ));
    
    $facebook->getAccessToken();
    
    $fb_user_id = $facebook->getUser();
    
    //check if user currently in db
    $user = $db->PDOquery("SELECT id, weights FROM users WHERE facebook_id = ?;", array($fb_user_id));
    if(empty($user))
    {
        //get likes
        $fbresult = $facebook->api('/me?fields=likes,gender,birthday');
        //calculate weights
        //$mapping from functions.php
        $user_weights = getWeightsVector($fbresult['likes']['data'], $mapping);
        
        //add to Users
        $insert_data = array(
            getAge($fbresult['birthday']),
            ($fbresult['gender']=='male') ? 'M' : 'K',
            weightsArrayToString($user_weights),
            $fbresult['id']
        );
        $user_id = $db -> PDOquery('INSERT INTO users (age, gender, weights, facebook_id) VALUES (?,?,?,?) RETURNING id;', $insert_data);
        $user_id = $user_id[0]['id'];
    }
    else
    {
        $user_id = $user[0]['id'];
        $user_weights = weightsStringToArray($user[0]['weights']);
    }
    
    array_push($user_weights, $user_id);
    array_push($user_weights, RATE_PRODUCT_COUNT);
//    if (!is_numeric($_GET['page']))
//    {
        $page=0;
        array_push($user_weights, 0);
//    }
//    else
//    {
//        $page = $_GET['page'];
//        array_push($user_weights, $page*RATE_PRODUCT_COUNT);
//    }
    
    //$weight_likes_query_for_santa from functions.php
    $result = $db -> PDOquery($weight_likes_query_for_santa, $user_weights);
    
    if (empty($result))
    {
        $output['recommendations'] = null;
        $output['next'] = null;
    }
    else
    {
        $output['recommendations'] = $result;
        $output['next'] = $_SERVER['SCRIPT_URI'];//.'?page='.($page+1);
    }
    $output['recommendation_id'] = $user_id;
    echo json_encode($output);
?>
